<?php

namespace app\index\model;

use think\Model;
use Carbon\Carbon;
use app\common\traits\model\TraitModel;
use think\exception\HttpException;
use think\Db;
/**
* 心愿单模型类
* @method createWish([['region' => 22, 'start_date' => '2016-12-13', 'end_date' => '2016-12-21', 'score' => 700, 'offer' => 97], ['region' => 19, 'start_date' => '2016-12-8', 'end_date' => '2016-12-10', 'score' => 652, 'offer' => 60]]);
* @method bool cancelMeetTheDemand(array|string $wish_id) 取消满足需求
* @method bool meetTheDemand(array|string $wish_id) 满足需求
* @method bool cancelWish() 取消心愿
*/
class Wishs extends Model
{
    protected $autoWriteTimestamp = 'timestamp';
    protected $createTime = 'created_at';
    protected $updateTime = 'updated_at';
	protected $type = [
		'region'=>'array'
	];	
    const POST_WISH_PRICE = 10;

    use TraitModel;
	public function getCityAttr($value){
		if($value==-1){
			return '';
		}
		$status = ['1'=>'北京','2'=>'上海','3'=>'三亚','4'=>'成都','5'=>'西安'];
	   return $status[$value];
	}
    public function users()
    {
        return $this->hasMany('app\user\model\WishUsers', 'wish_id');
    }
    /**
     * 发送通知
     * @param  array  $motifys_info [description]
     * @return [type]               [description]
     */
    public function notifys($motifys_info = [])
    {
        return  Notifys::createNotifys($motifys_info);
    }
    /**
     * 设置房车时间为满足心愿状态
     * @param [type] $caravan_id [description]
     * @param [type] $start_date [description]
     * @param [type] $end_date   [description]
     */
    public function setUserCaravanCarlendarIsWish($caravan_id, $start_date, $end_date = null)
    {
        return model('Calendar')->setUserCaravanCarlendarIsWish($caravan_id, $start_date, $end_date);
    }
    /**
     * 取消设置房车时间为心愿状态
     * @param [type] $caravan_id  [description]
     * @param [type] $cancel_date [description]
     */
    public function setUserCaravanCarlendarIsUnWish($caravan_id, $cancel_date)
    {
        return model('Calendar')->setUserCaravanCarlendarIsUnWish($caravan_id, $cancel_date);
    }
    /**
     * 校验房车是否可以满足心愿
     * @param  [type] $caravan_id [description]
     * @param  [type] $start_date [description]
     * @param  [type] $end_date   [description]
     * @return [type]             [description]
     */
    public function checkUserCaravanDateSetWish($caravan_id, $start_date, $end_date = null)
    {
        return model('Calendar')->checkUserCaravanDateSetWish($caravan_id, $start_date, $end_date);
    }
    /**
     * 获取用户积分
     * @return [type] [description]
     */
    public function getUserIntegral()
    {
        return model('Intergrates')->getUserIntegral();
    }
    /**
     * 消费积分
     * @param  [type] $intergrates [description]
     * @return [type]              [description]
     */
    public function reduceIntergrates($intergrates, $remark = '悬赏消费')
    {
        return model('Intergrates')->reduceIntergrates($intergrates, null, ['remark' => $remark], true);
    }
    /**
     * 增加积分
     * @param [type] $intergrates [description]
     * @param [type] $user_id     [description]
     */
    public function addIntergrates($intergrates, $user_id = null, $remark = '取消悬赏退还')
    {
        return model('Intergrates')->addIntergrates($intergrates, $user_id, ['remark' => $remark]);
    }
    /**
     * 获取用户房车信息
     * @param  [type] $user_id [description]
     * @param  string $field   [description]
     * @return [type]          [description]
     */
    public function getCaravanInfo($user_id, $field = '')
    {
        return model('user/CaravanInfos')->getCaravanInfo($user_id, $field);
    }
    /**
     * 创建心愿
     * @param  [type] $wish_info [description]
     * @return [type]            [description]
     */
    public function createWish($wish_info)
    {
        if (empty($wish_info)) {
            return false;
        }
        if (is_array($wish_info) && key($wish_info) !== 0) {
            $wish_info = [$wish_info];
        }
        $intergrates = $postwishprices = 0;
        foreach ($wish_info as $_wish_info) {
            if (!is_numeric($_wish_info['score']) || $_wish_info['score'] < 0) {
                // throw new HttpException(-1, "Integral can not be negative");
                $this->error = ['code' => -200, 'msg' => lang('Integral can not be negative or Integration format error')];
                return false;
            }
            $intergrates    += (int)$_wish_info['score'];
            $postwishprices += self::POST_WISH_PRICE;
        }
        if ($this->getUserIntegral() < $intergrates + $postwishprices) {
        	$this->error = ['code' => -300, 'msg' => lang('notEnough')];
        	//return 'notEnough';
            return false;
        }
        $this->startTrans();
        try {
            $this->reduceIntergrates($intergrates);
            $this->reduceIntergrates($postwishprices, '发布心愿单');
            foreach ($wish_info as $_wish_info) {
                self::create(array_merge($_wish_info, ['user_id' => self::getLoginUserInfo('id')]), true);
            }
            $this->commit();
        } catch (Exception $e) {
            $this->rollback();
			$this->error = ['code' => -200, 'msg' => lang('unknown error')];
            return false;
        }
        return true;        
    }
    /**
     * 获取用户心愿列表
     * @return [type] [description]
     */
    public function getWishList($querys = [])
    {
    	return self::getInfoList(array_merge($querys , ['user_id' => self::getLoginUserInfo('id')]));
    }
    /**
     * 获取心愿详情
     * @param  [type] $wish_id [description]
     * @param  string $field   [description]
     * @return [type]          [description]
     */
    public function getWish($where = [], $field = '')
    {
        if (empty($where)) {
            return ;
        }
        $wish = self::get($where);
        if ($field) {
            if (isset($wish->$field)) {
                return $wish->$field; 
            }
            return ;
        }
        return $wish;
    }
    /**
     * [getWishs description]
     * @param  array  $where [description]
     * @return [type]        [description]
     */
    private function getWishs($where = [])
    {
        return self::all($where);
    }
    /**
     * 获取心愿状态
     * @param  [type] $wish_id [description]
     * @return [type]          [description]
     */
    public function getWishStatus($where = [])
    {
        return $this->getWish($where, 'status');
    }
    /**
     * 修改心愿
     * @param  array  $where     [description]
     * @param  array  $wish_info [description]
     * @return [type]            [description]
     */
    public function updateWish($wish_id, $wish_info = [])
    {
        $wish = $this->getWish(['id' => $wish_id, 'user_id' => self::getLoginUserInfo('id')]);
        if ($wish->status === 0 && $wish->users()->count() == 0) {
            if (!is_numeric($wish_info['score']) || $wish_info['score'] < 0) {
            	 $this->error = ['code' => -200, 'msg' => lang('Integral can not be negative or Integration format error')];
                return false;
            } 
            if ($wish_info['score'] > $wish->score) {
                if ($this->getUserIntegral() < ($wish_info['score'] - $wish->score)) {
                    $this->error = ['code' => -300, 'msg' => lang('notEnough')];
                    return false;
                }
            }
            $intergrates = abs($wish_info['score'] - $wish->score);

            $this->startTrans();
            try {
                if ((int)$intergrates != 0) {
                    if ($wish_info['score'] > $wish->score) {
                        $this->reduceIntergrates($intergrates, '修改心愿补足差额');
                    }else{
                        $this->addIntergrates($intergrates, null, '修改心愿退还差额');
                    }
                }
                $this->update($wish_info, ['id' => $wish_id, 'user_id' => self::getLoginUserInfo('id')],true);
                $this->commit();   
            } catch (Exception $e) {
                $this->rollback();
				$this->error = ['code' => -200, 'msg' => lang('unknown error')];
                return false;
            }
            return true;
        }
		$this->error = ['code' => -200, 'msg' => lang('unknown error')];
        return false;
    }
    /**
     * 取消心愿
     * @param  [type] $wish_id [description]
     * @return [type]          [description]
     */
    public function cancelWish($wish_id)
    {
        $where = array_merge(['id' => ['in', $wish_id], 'user_id' => self::getLoginUserInfo('id'), 'status' => 0]);
        $wishs = $this->getWishs($where);
        if (!$wishs) {
            return false;
        }

        $this->startTrans();
        try {
            foreach ($wishs as $wish) {
                $meet_user_ids = $wish->users()->column('meet_user_id');
                $this->addIntergrates($wish->score, null, '取消心愿退还');
                foreach ($meet_user_ids as $meet_user_id) {
                    $this->syncCancelMeetTheDemand($wish->id, $meet_user_id);
                }
                $wish->users()->delete();
                $wish->delete(); 
            }
            $this->commit();
        } catch (Exception $e) {
            $this->rollback();
            return false;
        }
        return true;
    }
    /**
     * 完成心愿
     * @param  [type] $wish_id      [description]
     * @param  [type] $meet_user_id [description]
     * @return [type]               [description]
     */
    protected function meetWish($wish_id, $meet_user_id)
    {
        $wish = $this->getWish(['id' => $wish_id, 'status' => 0]);
        $wish->status = 99;
        $wish->save();
        $u = $wish->users()->where('meet_user_id', $meet_user_id)->update(['status' => 99]);

        $this->syncCancelWish($wish_id, self::createDateRange($wish->start_date, $wish->end_date));
    }
    /**
     * 设置房车状态
     * @param [type]  $caravan_id [description]
     * @param [type]  $start_date [description]
     * @param [type]  $end_date   [description]
     * @param integer $status     [description]
     * @param array   $querys     [description]
     * @param boolean $syn        [description]
     */
    private function setCaravanCarlendarIsOrders($caravan_id, $start_date, $end_date, $querys = ['orders' => ['not in', '0']], $syn = false)
    {
        return model('user/Calendar')->setUserCaravanCarlendarIsOrders($caravan_id, $start_date, $end_date, '', $querys, $syn);
    }
    /**
     * 根据心愿创建订单
     * @param  [type] $wish_id      [description]
     * @param  [type] $meet_user_id [description]
     * @return [type]               [description]
     */
    public function createOrder($wish_id, $meet_user_id,$order_info)
    {
        $wish = $this->getWish(['id' => $wish_id, 'status' => 0]);
        if (!$wish) {
            return false;
        }
        $this->startTrans();
        try {
            $this->meetWish($wish_id, $meet_user_id);
            $meet_user = $wish->users()->where(['meet_user_id' => $meet_user_id])->find();
            
            $this->setCaravanCarlendarIsOrders($meet_user['caravan_id'], $wish['start_date'], $wish['end_date']);
            model('Orders')->createOrder($order_info);//创建订单
            $this->addIntergrates($wish->score, $meet_user_id, '心愿悬赏');//增加积分
            $this->commit(); 
        } catch (Exception $e) {
            $this->rollback();
            return false;
        }
        $this->notifys(['users_id' => $meet_user_id, 'body' => '@wish']);
        return true;
    }
    public function toMe($wish_id = null)
    {
        $this->getWishs();
    }
    /**
     * 满足需求
     * @param [type] $wish_id [description]
     */
    public function meetTheDemand($wish_id)
    {
        $wishs = $this->getWishs(['id' => ['in', $wish_id], 'user_id' => ['NEQ', self::getLoginUserInfo('id')]]);
        if (!$wishs) {
            return false;
        }
        $caravan_id = $this->getCaravanInfo(['user_id' => self::getLoginUserInfo('id')], 'id');
        if (!$caravan_id) {
            return false;
        }
        $this->startTrans();
        try {
            foreach ($wishs as $wish) {
                if (!$wish->users) {
                    if (true == $this->checkUserCaravanDateSetWish($caravan_id, $wish->start_date, $wish->end_date)) {
                        //更新日历 锁定时间
                        $wish->users()->save(['meet_user_id' => self::getLoginUserInfo('id'), 'caravan_id' => $caravan_id]);
                        $this->setUserCaravanCarlendarIsWish($caravan_id, $wish->start_date, $wish->end_date);
                        $this->notifys(['users_id' => $wish->user_id, 'body' => '@wish']);
                    }   
                }
            }
            $this->commit();         
        } catch (Exception $e) {
            $this->rollback();
            return false;
        }
        return true;  
    }
    /**
     * 取消满足需求
     * @param  [type] $wish_id [description]
     * @return [type]          [description]
     */
    public function cancelMeetTheDemand($wish_id, $user_id = null)
    {
        if (is_scalar($wish_id)) {
            $wish_id = explode(',', $wish_id);
        }

        $user_id = $user_id  ? : self::getLoginUserInfo('id');

        $this->startTrans();
        try {
            $wishs = self::hasWhere('users', ['meet_user_id' => $user_id])->select();
            $this->syncCancelMeetTheDemand($wish_id, $user_id);
            foreach ($wishs as $wish) {
                if (in_array($wish->id, $wish_id)) {
                    $wish->users()->where(['meet_user_id' => $user_id])->delete();
                }
            }
            $this->commit();          
        } catch (Exception $e) {
            $this->rollback();
            return false;
        }
        return true;
    }
    /**
     * 同步取消需求
     * @param  [type] $wish_id [description]
     * @param  [type] $user_id [description]
     * @return [type]          [description]
     */
    protected function syncCancelMeetTheDemand($wish_id, $user_id = null)
    {
        if (is_scalar($wish_id)) {
            $wish_id = explode(',', $wish_id);
        }
        if ($caravan_id = $this->getCaravanInfo($user_id, 'id')) {
            $old_date = $all = [];
            $wishs = self::hasWhere('users', ['meet_user_id' => $user_id])->select();
            foreach ($wishs as $wish) {
                $all = array_merge($all, self::createDateRange($wish->start_date, $wish->end_date));
                if (!in_array($wish->id, $wish_id)) {
                    $old_date = array_merge($old_date, self::createDateRange($wish->start_date, $wish->end_date));
                }
            }

            if ($cancel_date = array_unique(array_diff($all, $old_date))) {
                    //更新日历 解锁锁定时间 setUserCaravanCarlendarIsUnLock
                $this->setUserCaravanCarlendarIsUnWish($caravan_id, $cancel_date);
            }
        }        
    }
    /**
     * 同步取消心愿
     * @param  [type] $wish_id [description]
     * @param  array  $dates   [description]
     * @return [type]          [description]
     */
    protected function syncCancelWish($wish_id, $dates = [])
    {
        $wishs = self::hasWhere('users', ['wish_id' => ['NEQ', $wish_id]])->where('user_id', self::getLoginUserInfo('id'))->select();
        foreach ($wishs as $wish) {
            $meet_user_ids = $wish->users()->where(['wish_id' => ['NEQ', $wish_id]])->column('meet_user_id');
            foreach ($meet_user_ids as $meet_user_id) {
                $this->syncCancelMeetTheDemand($wish->id, $meet_user_id);
            }
        }
    }
	
	/**
	 * 获取地址
	 */
	public function getAddress($array_address){
	    $address = Db::table('area')->where('AREA_CODE',$array_address)->value('AREA_NAME');
	    return $address;
	}
}
